/**
 * AI对话服务
 * 处理AI对话逻辑、流式响应、上下文管理
 * 集成后端API和WebSocket连接
 */
import { requestManager, generateId } from '../utils/index.js'
class AIDialogueService {
  constructor() {
    this.conversationHistory = []
    this.isStreaming = false
    this.currentStreamController = null
    this.ws = null
    this.baseURL = '/api'  // 使用代理路径
    this.wsURL = 'ws://localhost:3001'  // WebSocket直接连接
    this.requestManager = requestManager
    // this.connectWebSocket()
  }

  /**
   * 连接WebSocket
   */
  connectWebSocket() {
    try {
      this.ws = new WebSocket(this.wsURL)
      
      this.ws.onopen = () => {
        console.log('🔗 WebSocket连接已建立')
      }
      
      this.ws.onclose = () => {
        console.log('🔌 WebSocket连接已断开')
        // 尝试重连
        setTimeout(() => this.connectWebSocket(), 3000)
      }
      
      this.ws.onerror = (error) => {
        console.error('WebSocket错误:', error)
        // 如果WebSocket连接失败，标记为不可用
        this.ws = null
      }
    } catch (error) {
      console.error('WebSocket连接失败:', error)
      this.ws = null
    }
  }

  /**
   * 发送消息并获取AI响应
   * @param {string} userMessage - 用户消息
   * @param {Function} onStream - 流式响应回调
   * @param {Function} onComplete - 完成回调
   * @returns {Promise<Object>} AI响应消息
   */
  async sendMessage(userMessage, onStream, onComplete) {
    if (this.isStreaming) {
      throw new Error('Another conversation is in progress')
    }

    // 创建AI响应消息对象（不添加到历史记录，由前端管理）
    const aiMsg = {
      id: this.generateId(),
      role: 'assistant',
      content: '',
      timestamp: Date.now(),
      isStreaming: true
    }

    this.isStreaming = true
    this.currentStreamController = new AbortController()

    try {
      //先不使用websocket，使用http api
      this.ws = false;
      // 优先使用WebSocket，如果不可用则降级到HTTP API
      if (this.ws && this.ws.readyState === WebSocket.OPEN) {
        console.log('📡 使用WebSocket发送消息')
        await this.sendViaWebSocket(userMessage, aiMsg, onStream, onComplete)
      } else {
        console.log('🌐 使用HTTP API发送消息')
        await this.sendViaHTTP(userMessage, aiMsg, onStream, onComplete)
      }
      aiMsg.isStreaming = false
      return aiMsg
    } catch (error) {
      if (error.name === 'AbortError') {
        console.log('Streaming was aborted')
        aiMsg.content = '响应被中断'
      } else {
        console.error('AI response error:', error)
        aiMsg.content = '抱歉，发生了错误，请重试'
      }
      aiMsg.isStreaming = false
      throw error
    } finally {
      this.isStreaming = false
      this.currentStreamController = null
    }
  }

  /**
   * 通过WebSocket发送消息
   */
  async sendViaWebSocket(userMessage, aiMsg, onStream, onComplete) {
    return new Promise((resolve, reject) => {
      const conversationId = this.generateId()
      
      // 设置消息处理器
      const handleMessage = (event) => {
        try {
          const data = JSON.parse(event.data)
          
          switch (data.type) {
            case 'ai_response':
              if (data.conversationId === conversationId) {
                aiMsg.content += data.data.content || ''
                if (onStream) onStream(aiMsg)
              }
              break
            case 'ai_complete':
              if (data.conversationId === conversationId) {
                this.ws.removeEventListener('message', handleMessage)
                if (onComplete) onComplete(aiMsg)
                resolve(aiMsg)
              }
              break
            case 'ai_error':
              this.ws.removeEventListener('message', handleMessage)
              reject(new Error(data.error))
              break
          }
        } catch (error) {
          this.ws.removeEventListener('message', handleMessage)
          reject(error)
        }
      }
      
      this.ws.addEventListener('message', handleMessage)
      
      // 发送消息
      this.ws.send(JSON.stringify({
        type: 'ai_chat',
        message: userMessage,
        conversationId
      }))
    })
  }

  /**
   * 通过HTTP API发送消息
   */
  async sendViaHTTP(userMessage, aiMsg, onStream, onComplete) {
    try {
      const conversationId = this.generateId()
      
      // const response = await this.requestManager.post('/api/deepseek/chat', 
      //       {
      //         message: userMessage,
      //         conversationId
      //       }, 
      //       {
      //         requestId: conversationId,
      //         timeout: 30000
      //       }
      // )


      // 使用统一请求管理器与相对路径，避免开发环境CORS问题
      const resp = await this.requestManager.post(`${this.baseURL}/deepseek/chat`, {
        message: userMessage,
        conversationId
      }, {
        requestId: conversationId,
        timeout: 30000
      })

      const data = resp?.data

      if (data && data.success && data.data) {
        const content = data.data
        const words = content.split('');
        
        for (let i = 0; i < words.length; i++) {
          aiMsg.content += words[i];
          if (onStream) onStream(aiMsg);
          await new Promise(resolve => setTimeout(resolve, 50));
        }
        
        if (onComplete) onComplete(aiMsg);
      } else {
        const errMsg = (data && data.error) || 'Unknown error'
        throw new Error(errMsg)
      }
    } catch (error) {
      console.error('HTTP API调用失败:', error)
      throw error
    }
  }

  /**
   * 模拟流式响应
   * @param {Object} aiMsg - AI消息对象
   * @param {Function} onStream - 流式回调
   * @param {Function} onComplete - 完成回调
   */
  async simulateStreamingResponse(aiMsg, onStream, onComplete) {
    // 模拟AI响应内容
    const responses = [
      "你好！我是AI助手，很高兴为您服务。",
      "这是一个基于虚拟列表和TTS优化的AI对话系统。",
      "系统采用了多项性能优化技术：",
      "1. 虚拟列表技术，支持大量消息的流畅滚动",
      "2. TTS语音合成，支持文本分段和并发处理",
      "3. 智能缓存机制，提升响应速度",
      "4. 流式输出，提供实时的交互体验",
      "有什么我可以帮助您的吗？"
    ]

    let currentResponse = ""
    let responseIndex = 0

    // 模拟逐字输出
    while (responseIndex < responses.length) {
      if (this.currentStreamController?.signal.aborted) {
        throw new Error('AbortError')
      }

      const currentText = responses[responseIndex]
      const words = currentText.split('')
      
      for (let i = 0; i < words.length; i++) {
        if (this.currentStreamController?.signal.aborted) {
          throw new Error('AbortError')
        }

        currentResponse += words[i]
        aiMsg.content = currentResponse
        
        // 调用流式回调
        if (onStream) {
          onStream(aiMsg)
        }

        // 模拟打字延迟
        await new Promise(resolve => setTimeout(resolve, 50))
      }

      currentResponse += "\n\n"
      responseIndex++
    }

    // 完成回调
    if (onComplete) {
      onComplete(aiMsg)
    }
  }

  /**
   * 停止当前流式响应
   */
  stopStreaming() {
    if (this.currentStreamController) {
      this.currentStreamController.abort()
    }
  }

  /**
   * 获取对话历史
   * @returns {Array} 对话历史数组
   */
  getConversationHistory() {
    return [...this.conversationHistory]
  }

  /**
   * 清空对话历史
   */
  clearHistory() {
    this.conversationHistory = []
  }

  /**
   * 生成唯一ID
   * @returns {string} 唯一ID
   */
  generateId() {
    return generateId('ai')
  }

  /**
   * 获取对话统计信息
   * @returns {Object} 统计信息
   */
  getStats() {
    const userMessages = this.conversationHistory.filter(msg => msg.role === 'user')
    const aiMessages = this.conversationHistory.filter(msg => msg.role === 'assistant')
    
    return {
      totalMessages: this.conversationHistory.length,
      userMessages: userMessages.length,
      aiMessages: aiMessages.length,
      isStreaming: this.isStreaming,
      requestManagerStats: this.requestManager.getStats()
    }
  }

  /**
   * 获取活跃请求列表
   * @returns {Array} 活跃请求ID列表
   */
  getActiveRequests() {
    return this.requestManager.getActiveRequests()
  }

  /**
   * 取消所有请求
   */
  cancelAllRequests() {
    this.requestManager.cancelAllRequests()
    this.stopStreaming()
  }
}

// 创建单例实例
const aiDialogueService = new AIDialogueService()

export default aiDialogueService
